<?php
	//由于为专用系统,只通过用户ID,密码进入 或者已有session的情况
	include_once("./public/common.php");
	include_once("./public/verify.php");
	$sessionId = getSessionPara('sessionId');
	$uid = getSessionPara('uid');
	$level = getSessionPara('level');
	$postMD5SessionId = getPOSTPara('pms');
	$verifyFlag = false;
	$salt = '';
	$retFlag = true;//总flag
	
	if($sessionId && $postMD5SessionId && strcmp(md5($sessionId),substr(urldecode($postMD5SessionId),3,32))==0)$verifyFlag = true;//从曲线返回到此页面时
	if($sessionId && $uid && $level)$verifyFlag = true;//已有session时

	//+++2015年6月12日22:19:30 用于同一个浏览器中需要登录不同用户时使用
	$uid2 = getPOSTPara('uid');
	if($uid2 != NULL && $uid2 != $uid){
		$verifyFlag = false;
	}
	//+++
	
	
	if(!$verifyFlag){//没session，第一次进入
		
		$uid = getPOSTPara('uid');
		$password = getPOSTPara('password');
		
		//检查参数合法性
		if(!is_numeric($uid)){
			echo alertHtmlString("404");
			$retFlag = false;
			return false;
		}
		$uid = intval($uid);
		$password = strFilter($password);

		//检查验证码
		if($debugMode == false){
			$capt = getPOSTPara('captcha');
			$sessionCapt = empty($_SESSION['captcha'])?null:$_SESSION['captcha'];
			if($capt == null  || trim(strtolower($capt)) != $sessionCapt) {
				echo "captcha wrong!";
				unset($_SESSION['captcha']);
				$retFlag = false;
				return false;
			}

			unset($_SESSION['captcha']);
		}
		//获取level等相关信息
		include_once("./public/opDB.php");
		$res = mysql_query("select `password`,`delflag`,`level` from `user` where uid=".$uid." limit 0,1");
		if(!$res || empty($res)){
			echo "404";
			$retFlag = false;
			return false;
		}
		$res = mysql_fetch_array($res);
		$pwd = $res['password'];
		$level = $res['level'];
		$delflag = $res['delflag'];
		//echo $pwd,"|",$password;
		if($delflag != 0 || strcmp($pwd,$password)!=0 ){
			echo "fail to pass the verification";
			$retFlag = false;
			return false;
		}
		//echo "welcome";
	}	
	
	
	//没有session但通过验证的,为其设置session
	if(!$postMD5SessionId){
		$saltlen = mt_rand(5,11);
		$salt = '';
		for($i=0;$i<$saltlen;++$i){
			$salt .= chr(ord('A')+mt_rand(0,25));
		}
		$saltLeft = '';
		for($i=0;$i<3;++$i){
			$saltLeft .= chr(ord('A')+mt_rand(0,25));
		}
		$saltRight = '';
		for($i=0;$i<5;++$i){
			$saltRight .= chr(ord('A')+mt_rand(0,25));
		}
		$tp1 = $saltLeft.md5($salt).$saltRight;
		$_SESSION['sessionId'] = $tp1;
		$_SESSION['uid'] = $uid;
		$_SESSION['level'] = $level;
		
		//再用cookie存一份,名字均+c
		// setCookie('csessionId',$tp1,time()+3600);
		// setCookie('cuid',$uid,time()+3600);
		// setCookie('clevel',$level,time()+3600);
		
		$postMD5SessionId = $saltLeft.md5($_SESSION['sessionId']).$saltRight;
		//echo '<p>'.$_SESSION['pms'] .'</p>';
		//echo '<p>'.$postMD5SessionId.'</p>';
	}
?>